/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package negocio;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import utilitarios.Formato;

/**
 *
 * @author renan
 */
public class NegocioDAO extends Formato {

    protected Erros erros;
    private static NegocioDAO me;
    private EntityManagerFactory emf;

    public NegocioDAO() {
        erros = new Erros();
        emf = Persistence.createEntityManagerFactory("EmiratesPU");
    }

    public static NegocioDAO getInstance() {
        if (me == null) {
            me = new NegocioDAO();
        }
        return me;
    }

    public EntityManager getEntityManager() {
        EntityManager toReturn = emf.createEntityManager();
        toReturn.getTransaction().begin();
        return toReturn;
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> getList(Class<T> classToCast, String jpql, Object... parameters) {
        List<T> toReturn = null;
        EntityManager em = getEntityManager();
        Query qr = em.createQuery(jpql);
        for (int i = 0; i < parameters.length; i++) {
            qr.setParameter(i + 1, parameters[i]);
        }
        toReturn = qr.getResultList();
        em.getTransaction().commit();
        em.close();
        return toReturn;
    }

    public <T> T getEntity(Class<T> entityClass, Serializable pk) {
        EntityManager em = getEntityManager();
        T toReturn = em.find(entityClass, pk);
        em.getTransaction().commit();
        em.close();
        return toReturn;
    }
 
}
